package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.EducationInfo;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.EducationInfoRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class EducationInfoService {

    private final EducationInfoRepository educationInfoRepository;
    private final ApplicationRepository applicationRepository;

    public EducationInfoService(EducationInfoRepository educationInfoRepository, ApplicationRepository applicationRepository) {
        this.educationInfoRepository = educationInfoRepository;
        this.applicationRepository = applicationRepository;
    }

    public EducationInfo createEducationInfo(Long applicationId, EducationInfo educationInfo) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        educationInfo.setApplication(application);
        educationInfo.setCreatedAt(LocalDateTime.now());
        educationInfo.setUpdatedAt(LocalDateTime.now());
        return educationInfoRepository.save(educationInfo);
    }

    public List<EducationInfo> getEducationInfoByApplicationId(Long applicationId) {
        return educationInfoRepository.findByApplicationId(applicationId);
    }

    public Optional<EducationInfo> getEducationInfoById(Long id) {
        return educationInfoRepository.findById(id);
    }

    public EducationInfo updateEducationInfo(Long id, EducationInfo updatedEducationInfo) {
        EducationInfo existingEducationInfo = educationInfoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("EducationInfo not found"));

        existingEducationInfo.setSchoolName(updatedEducationInfo.getSchoolName());
        existingEducationInfo.setEducationType(updatedEducationInfo.getEducationType());
        existingEducationInfo.setMajor(updatedEducationInfo.getMajor());
        existingEducationInfo.setDegree(updatedEducationInfo.getDegree());
        existingEducationInfo.setGraduationDate(updatedEducationInfo.getGraduationDate());
        existingEducationInfo.setGraduationCertificateNo(updatedEducationInfo.getGraduationCertificateNo());
        existingEducationInfo.setDegreeCertificateNo(updatedEducationInfo.getDegreeCertificateNo());
        existingEducationInfo.setUpdatedAt(LocalDateTime.now());

        return educationInfoRepository.save(existingEducationInfo);
    }

    public void deleteEducationInfo(Long id) {
        educationInfoRepository.deleteById(id);
    }
}

